package ai.modules;

import util.List;
import ai.AIConstant;
import ai.PossibleAssignment;
import ai.Task;
import ai.TaskFactory;
import ai.tasks.BuildUnitTask;
import engine.GameEngine;
import engine.data.Unit;

public class ProductionAllocationModule {

	public final static void generateProductionTasks() {
		for (int n = 0; n < TaskFactory.tasks.size(); n++) {
			if (((Task) TaskFactory.tasks.get(n)).status == AIConstant.STATUS_WAIT_4_RESOURCES) {
				List resourcesNeeded = ((Task) TaskFactory.tasks.get(n)).getResourcesNeeded();
				for (int i = 0; i < resourcesNeeded.size(); i++) {
					TaskFactory.productionTasks
					.add(new BuildUnitTask());
				}
			}
		}		
	}

	public final static void generateAssignments() {
		// listAsset contains a list of all assets (for instance ships)
		TaskFactory.listPossAssignment.clear();
		for (int f = 0; f < GameEngine.currPlayer.units.size(); f++) {
			for (int n = 0; n < TaskFactory.tasks.size(); n++) {
				if (!((Unit) GameEngine.currPlayer.units
						.get(f)).played && ((Task) TaskFactory.tasks.get(n))
						.isTaskSuitable((Unit) GameEngine.currPlayer.units
								.get(f))) {
					TaskFactory.listPossAssignment
							.add(new PossibleAssignment(
									(Task) TaskFactory.tasks.get(n),
									(Unit) GameEngine.currPlayer.units.get(f)));
				}
				((Task) TaskFactory.tasks.get(n)).assignedUnits
						.clear();
			}
			((Unit) GameEngine.currPlayer.units.get(f)).assignedTask = null;
		}
	}

	public final static void sortAssignments() {
		ai.Sort.quickSort(TaskFactory.listPossAssignment, 0,
				TaskFactory.listPossAssignment.size() - 1);
	}

	public final static void assignTasks() {
		for (int n = 0; n < TaskFactory.listPossAssignment.size(); n++) {
			PossibleAssignment assignment = ((PossibleAssignment) TaskFactory.listPossAssignment
					.get(n));
			if (assignment.possibleTaskDoer.assignedTask == null
					&& assignment.task.assignedUnits.size() < assignment.task.resourcesMax) {
				// System.out.println(assignment.possibleTaskDoer + " is
				// assigned to " + assignment.task);
				assignment.task.assign(assignment.possibleTaskDoer);
				assignment.possibleTaskDoer.assignedTask = assignment.task;
				if (assignment.task.assignedUnits.size() >= assignment.task.resourcesMin)
					assignment.task.status = ai.AIConstant.STATUS_IN_PROGRESS;
			}
		}
	}

	public static final String getString() {
		StringBuffer res = new StringBuffer(
				"AI Resouce Allocation Module - turn ").append(GameEngine.turn)
				.append(" - civ ").append(GameEngine.currPlayer.civilization)
				.append(" : \n");
		for (int n = 0; n < TaskFactory.listPossAssignment.size(); n++) {
			res.append(((PossibleAssignment) TaskFactory.listPossAssignment
					.get(n)).toString());
		}
		return res.toString();
	}

}
